<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // 1.  已知字符串"aabccd"编程实现以下功能。
    // (1) 字符串去重  "abcd"
    // (2) 统计每个字符出现的次数，结果显示   a2b1c2d1     字符统计(每个字符出现的总次数)

    // (3)(原始字符串：aaaabbbbbbbccdaaaaa；压缩后：a4b7c2d1a5)  压缩统计 (相邻字符重复的次数)


    var str = "aabccd";
    var uniStr = "";
    for (var char of str) {
        if (uniStr.indexOf(char) == -1) {
            uniStr += char;
            // uniStr = uniStr.concat(char);
        }
    }
    console.log(uniStr); // "abcd"

    // (2) 
    /* var countStr = "";
    for(var i=0;i<uniStr.length;i++){ // "abcd"=> 每一个
        var uniChar = uniStr.charAt(i); //"a"
        var count = 0;
        for(var j = 0; j < str.length; j++){
            var item = str.charAt(j);
            if(uniChar == item){
                count++;
            }
        }
        countStr += uniChar+count;
    } 
    console.log(countStr); */


    /* var countStr = "";
    for(var i=0;i<uniStr.length;i++){ // "abcd"=> 每一个
        var uniChar = uniStr.charAt(i); //"a"
        var reg = new RegExp(uniChar,"g"); //   /a/g
        var list = str.match(reg);
        console.log(reg,list);
        countStr += uniChar+list.length;
    } 
    console.log(countStr); */

    // var arr = [ "a" ,"a", "b" ,"c" ,"c" ,"d"];
    /* var str = "aabccd";
    var obj = {};
    for (var char of str) { // "aabccd"  => "a" "a" "b" "c" "c" "d"
        if (obj[char]) { // 把每一个字符 作为对象的键名(键名唯一)
            obj[char]++;  //  obj[char] = obj[char] + 1
        } else {
            obj[char] = 1;
        }
    }
    console.log(obj);

    var countStr = "";
    for(var key in obj){
        console.log(key,obj[key]);
        countStr += key + obj[key];
    }
    console.log(countStr); */

    // (3)(原始字符串：aaaabbbbbbbccdaaaaa；压缩后：a4b7c2d1a5)  压缩统计 (相邻字符重复的次数)

    var str = "aaaabbbbbbbccdaaaaa";
    var count = 0;
    var countStr = "";
    for(var i = 0; i < str.length;i++){
        if(str.charAt(i) == str.charAt(i+1)){
            count++;
        }else{
            count++;
            countStr += str.charAt(i) + count;
            count = 0;  //重置为0 用于下次重新计数
        }
    }
    console.log(countStr);



</script>

</html>